package com.yange.accountbook.ui

import androidx.recyclerview.widget.LinearLayoutManager
import com.lxj.xpopup.XPopup
import com.yange.accountbook.databinding.HomeActivityLayoutBinding
import com.yange.accountbook.entity.BooksEntity
import com.yange.accountbook.entity.IconEntity
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.popup.IconPopup
import com.yange.accountbook.ui.adapter.BookListAdapter
import com.yange.accountbook.utils.showToast
import com.zhuangku.app.widget.EmptyView

class HomeActivity : BaseActivity<HomeActivityLayoutBinding>() {

    lateinit var emptyView: EmptyView

    lateinit var myAdapter: BookListAdapter

    override fun getViewBinding() = HomeActivityLayoutBinding.inflate(layoutInflater)

    override fun init() {
        emptyView = EmptyView(this)
        myAdapter = BookListAdapter()
        myAdapter.setEmptyView(emptyView)
        myAdapter.setOnItemClickListener { adapter, view, position ->
            //跳转到账本详情
            var item = adapter.getItem(position) as BooksEntity
            BookDetailActivity.start(this, item)

        }
        getBookList()
        binding.listBook.layoutManager = LinearLayoutManager(this)
        binding.listBook.adapter = myAdapter
        binding.tvAdd.setOnClickListener {
            //新增账本
            XPopup.Builder(this)
                .asCustom(IconPopup(this, object : IconPopup.AddListener {
                    override fun success(icon: IconEntity) {
                        commit(icon.icon, icon.name)
                    }
                }, IconEntity()))
                .show()
        }
    }

    //新建账本
    private fun commit(icon: String, name: String) {
        RetrofitClient.getInstance().invokePostBody(
            this, Api.BOOK_SAVE, mapOf(
                "icon" to icon,
                "name" to name
            )
        ).subscribe(object : RecObserver<BaseResponse<Any>>(this, true, false) {
            override fun onSuccess(t: BaseResponse<Any>?) {
                getBookList()
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }

        })
    }

    /**
     * 获取账本详情
     */
    private fun getBookList() {
        RetrofitClient.getInstance().invokeGet(this, Api.BOOK_LIST, mapOf())
            .subscribe(object : RecObserver<BaseResponse<List<BooksEntity>>>(this, false, false) {
                override fun onSuccess(t: BaseResponse<List<BooksEntity>>?) {
                    myAdapter.setNewInstance(t?.data as MutableList<BooksEntity>?)
                }

                override fun onFail(msg: String, code: Int) {

                }
            })
    }


}